package com.fruit.service.order.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.GoodsContant;
import com.fruit.mapper.order.FruitTreeMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.service.order.FruitTreeUnbindManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;


/**
 * 
 * 解除果树绑定关系类
 *
 * @author shibeilei
 * @version 2017.11.30 19:20
 *
 */
@Slf4j
@Service
public class FruitTreeUnbindService implements FruitTreeUnbindManager {
	
	@Autowired
	private FruitTreeMapper fruitTreeMapper;

	@Autowired
	private PayMapper payMapper;

	@Override
	public Map<String, Object> updateFruitUnbind(String tradeId, String curTime) {
		Map<String, Object> resMap = new HashMap<String, Object>();

		log.info("[{}]-【解除果树绑定关系】-【开始】", tradeId, curTime);
		try {
			log.info("[{}]-【解除果树绑定关系】-【获取基地区域】", tradeId);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("isBinding", GoodsContant.Binding.YES.getValue());
			params.put("curTime", curTime);
			List<Long> agcList = fruitTreeMapper.getEndBindAreaCountId(params);
			if (agcList == null || agcList.size() == 0) {
				log.info("[{}]-【解除果树绑定关系】-【没有要解绑基地】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "没有要解绑基地"));
				return resMap;
			} else {
				for (long agcId : agcList) {
					resMap = updateFruitUnbind(agcId, tradeId, curTime);
					ResultInfo ri = (ResultInfo) resMap.get("result");
					if (ResultInfo.ERROR.equals(ri.getState())) {
						return resMap;
					}
				}
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "解绑成功"));
				return resMap;
			}
		} catch (Exception e) {
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "解除果树绑定关系异常", null, ResultInfo.ROLLBACK));
			log.error("[{}]-【解除果树绑定关系】-【异常】-【{}：{}】----{}", tradeId, "exception", "解除果树绑定关系异常",
					CustomUtil.getStackTraceAsString(e));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			if (ResultInfo.ERROR.equals(ri.getState())) {
				log.error("[{}]-【解除果树绑定关系】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
			} else {
				log.info("[{}]-【解除果树绑定关系】-【成功】", tradeId);
			}
			log.info("[{}]-【解除果树绑定关系】-【结束】", tradeId);
		}

	}
	/**
	 * 解除果树绑定关系
	 * @param agcId agcId
	 * @param tradeId tradeId
	 * @param curTime curTime
	 * @return 解除果树绑定关系结果
	 * @author shibeilei
	 * @version 2017
	 */
	public Map<String, Object> updateFruitUnbind(long agcId, String tradeId, String curTime) {
		log.info("[{}]-【解除果树绑定关系】-【解绑日期：{}】", tradeId, curTime);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("agcId", agcId);
			params.put("curTime", curTime);
			params.put("isBinding", GoodsContant.Binding.YES.getValue());
			List<Long> listTree = fruitTreeMapper.getEndBindingFruit(params);
			if (listTree == null || listTree.size() == 0) {
				log.info("[{}]-【解除果树绑定关系】-【没有要解绑的果树】", tradeId);
			} else {
				log.info("[{}]-【解除果树绑定关系】-【解绑数量：{}】", tradeId, listTree.size());
				int num = 1000;
				int start = 0;
				int end = -1;
				int m = listTree.size() % num;
				int n = listTree.size() / num;
				if (n > 0) {
					for (int i = 0; i < n; i++) {
						log.info("[{}]-【解除果树绑定关系】-【分批处理，解绑数量：{}】", tradeId, num);
						start = end + 1;
						end = end + num;
						params.clear();
						params.put("bindingIds", listTree.subList(start, end + 1));
						params.put("isBinding", GoodsContant.Binding.NO.getValue());
						int upNum = fruitTreeMapper.updateFruitNotUserBinding(params);
						if (num != upNum) {
							resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "num_error", "解绑数量错误", null,
									ResultInfo.ROLLBACK));
							return resMap;
						}
					}
				}
				if (m > 0) {
					log.info("[{}]-【解除果树绑定关系】-【分批处理，解绑数量：{}】", tradeId, m);
					start = end + 1;
					end = end + m;
					params.clear();
					params.put("bindingIds", listTree.subList(start, end + 1));
					params.put("isBinding", GoodsContant.Binding.NO.getValue());
					int upNum = fruitTreeMapper.updateFruitNotUserBinding(params);
					if (m != upNum) {
						resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "num_error", "解绑数量错误", null,
								ResultInfo.ROLLBACK));
						return resMap;
					}
				}
				params.clear();
				params.put("takeNum", listTree.size());
				params.put("takeState", "min");
				params.put("id", agcId);
				int resNum = payMapper.updateAreaGoodsTakeNumByMap(params);
				if (resNum != 1) {
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "update_error", "更新库存失败", null,
							ResultInfo.ROLLBACK));
					return resMap;
				}
			}
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "解绑成功"));
			return resMap;
		} catch (Exception e) {
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "解除果树绑定关系异常", null, ResultInfo.ROLLBACK));
			return resMap;
		}
	}

}
